# -*-coding: UTF-8 -*-
# @File : ReportUtil .py
# author: huangchen
# Time：2024/1/4
import json
import os
import shutil
import subprocess
from config.GlobalVar import G
from handler.LoggerHandler import logger


class ReportUtil:
    def __init__(self):
        self.log = logger()

    def run_bat(self, file):
        p = subprocess.Popen("cmd.exe /c" + file, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        curline = p.stdout.readline()
        while (curline != b''):
            print(curline)
            curline = p.stdout.readline()
        p.wait()
        print(p.returncode)

    def del_old_result(self):
        self.log.info("删除旧的结果集……")
        if os.path.exists(G.ALLURE_RESULT_PATH):
            shutil.rmtree(G.ALLURE_RESULT_PATH)

    def del_old_screenshot(self):
        self.log.info("删除旧的截图……")
        if os.path.exists(G.SCREENSHOT_DIR):
            shutil.rmtree(G.SCREENSHOT_DIR)

    def generate_report(self, result_path=None, report_path=None, result_history_dir=None, report_history_dir=None):
        self.log.info("生成报告……")
        if result_path is None:
            result_path = G.ALLURE_RESULT_PATH
        if report_path is None:
            report_path = G.ALLURE_REPORT_END_PATH
        if result_history_dir is None:
            result_history_dir = os.path.join(G.ALLURE_RESULT_PATH, "history")
        # 如果不存在则先创建文件夹
        if not os.path.exists(result_history_dir):
            os.mkdir(result_history_dir)
        os.system(f"allure generate {result_path} -o {report_path} --clean")
        # 将report的history复制到results的history中
        if report_history_dir is None:
            report_history_dir = os.path.join(G.ALLURE_REPORT_END_PATH, "history")
        files = os.listdir(report_history_dir)
        for file in files:
            shutil.copy(os.path.join(report_history_dir, file), result_history_dir)

    # 设置报告窗口的标题
    def set_windows_title(self, report_title_filepath=None):
        """
        通过修改allure-html目录下的index.html文件，设置打开的 Allure 报告的浏览器窗口标题文案
        @return:
        """
        if report_title_filepath is None:
            report_title_filepath = os.path.join(G.ALLURE_REPORT_END_PATH, "index.html")
        # 定义为只读模型，并定义名称为: f
        with open(report_title_filepath, 'r+', encoding="utf-8") as f:
            # 读取当前文件的所有内容
            all_the_lines = f.readlines()
            f.seek(0)
            f.truncate()
            # 循环遍历每一行的内容，将 "Allure Report" 全部替换为 → new_title(新文案)
            for line in all_the_lines:
                f.write(line.replace("Allure Report", G.ALLURE_REPORT_NAME))
            # 关闭文件
            f.close()

        # 修改Allure报告Overview的标题文案

    def set_report_name(self, title_filepath=None):
        """
        通过修改allure-html目录下的widgets/summary.json, 修改Allure报告Overview的标题文案
        @return:
        """
        if title_filepath is None:
            title_filepath = os.path.join(G.ALLURE_REPORT_END_PATH, "widgets", "summary.json")
        # 读取summary.json中的json数据，并改写reportName
        with open(title_filepath, 'rb') as f:
            # 加载json文件中的内容给params
            params = json.load(f)
            # 修改内容
            params['reportName'] = G.ALLURE_REPORT_NAME
            # 将修改后的内容保存在dict中
            new_params = params
        # 往summary.json中，覆盖写入新的json数据
        with open(title_filepath, 'w', encoding="utf-8") as f:
            json.dump(new_params, f, ensure_ascii=False, indent=4)

    def set_report_env_on_html(self, env_info: dict):
        """
         在allure-html报告中往widgets/environment.json中写入环境信息,
            格式参考如下：[{"values":["Auto Test Report"],"name":"report_title"},{"values":["autotestreport_"]]
        """
        envs = []
        for k, v in env_info.items():
            envs.append({
                "name": k,
                "values": [v]
            })
        with open(os.path.join(G.ALLURE_REPORT_END_PATH, "widgets", "environment.json"), 'w', encoding="utf-8") as f:
            json.dump(envs, f, ensure_ascii=False, indent=4)


if __name__ == '__main__':
    r = ReportUtil()
    r.set_windows_title()
    r.set_report_name()
